package com.example.imooccommon.store;

import com.example.imooccommon.util.CommonUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Arrays;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author Anita
 * @Date 2018/1/18 10:46
 */
@Slf4j
@Component
public class QiniuWrapper implements InitializingBean {


//    private static final String CONFIG_BUCKET="qiniu.bucket";
//
//    private static final String CONFIG_AK="qiniu.accesskey";
//    private static final String CONFIG_SK="qiniu.secretkey";
//    private static final String CONFIG_CDN="qiniu.cdns";

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.accesskey}")
    private String accesskey;

    @Value("${qiniu.secretkey}")
    private String secretkey;

    @Value("${qiniu.cdns}")
    private String cdns;



    private  Auth auth;
    private  UploadManager uploadManager;

    private  String bucketName;

//    @Autowired
//    private  Environment environment;

    /**
     * 从外部文件中初始化七牛存储相关的配置信息
     */
//    @Override
//    public void afterPropertiesSet() throws Exception {
//        auth = Auth.create(environment.getProperty(CONFIG_AK), environment.getProperty(CONFIG_SK));
//        log.info("ak:{}",environment.getProperty(CONFIG_AK));
//        Configuration cfg = new Configuration(Zone.zone0());//设置空间上传域名
//        uploadManager = new UploadManager(cfg);
//        bucketName = environment.getProperty(CONFIG_BUCKET);
//        String cdn = environment.getProperty(CONFIG_CDN);
//
//    }
    @Override
    public void afterPropertiesSet() throws Exception {
        auth = Auth.create(accesskey, secretkey);
        Configuration cfg = new Configuration(Zone.zone0());//设置空间上传域名
        uploadManager = new UploadManager(cfg);
        bucketName = bucket;
    }

    /**
     * 上传文件
     * @param data 二进制格式的文件内容
     * @param key 文件在七牛中的key
     * @param update 是否是更新
     * @return
     */
    public  String upload(byte[] data,String key,boolean update){
        try {
            String token = update?auth.uploadToken(bucketName,key):auth.uploadToken(bucketName);
            Response response = uploadManager.put(data, getFullKey(data, key), token);
            DefaultPutRet ret = response.jsonToObject(DefaultPutRet.class);
            return ret.key;
        } catch (QiniuException e) {
            log.error("upload file to qiniu cloud storage failed",e);
        }
        return null;
    }

    private static String getFullKey(byte[] data,String key){
        FileType type= FileTypeHelper.getType(data);
        if(type!=null){
            return key+"."+type.name().toLowerCase();
        }else{
            return key;
        }
    }

    public  String getUrl(String key){
        if(!StringUtils.isEmpty(key)){
            return auth.privateDownloadUrl("http://"+ cdns +"/"+key);
        }
        return null;
    }
}
